package org.mbds.android.sismapp.network;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import org.mbds.android.sismapp.SismappApplication;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

public class SismappNetworkTools {
	
	private static WifiManager wifiManager = (WifiManager) SismappApplication.getAppContext().getSystemService(Context.WIFI_SERVICE);
	private static boolean isWifiActivatedByApplication = false;
	private static boolean isWifiStateOk = false;
	
	public static byte[] getLocalIPAddress() {
	    try { 
	        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
	            NetworkInterface intf = en.nextElement(); 
	            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
	                InetAddress inetAddress = enumIpAddr.nextElement(); 
	                if (!inetAddress.isLoopbackAddress()) { 
	                    if (inetAddress instanceof Inet4Address) { 
	                    	// IPv4 
	                        return inetAddress.getAddress(); 
	                    } 
	                    // IPv6?
	                    return inetAddress.getHostAddress().getBytes();  
	                } 
	            } 
	        } 
	    } catch (SocketException ex) { 
	        //Do something 
	    } catch (NullPointerException ex) { 
	        //Do something 
	    } 
	    return null; 
	}

	public static String getDottedDecimalIP() {
		byte[] ipAddr = getLocalIPAddress();
	    //convert to dotted decimal notation:
	    if (ipAddr==null || ipAddr.length==0)
	    	return "";
	    String ipAddrStr = "";
	    for (int i=0; i<ipAddr.length; i++) {
	        if (i > 0) {
	            ipAddrStr += ".";
	        }
	        ipAddrStr += ipAddr[i]&0xFF;
	    }
	    return ipAddrStr;
	}
	/*************************************/
    /* Enable/Disable the WiFi interface */
    /*************************************/
	public static void enableWifi(boolean yes) {
		if (yes) {
			if (!wifiManager.isWifiEnabled()) {
				wifiManager.setWifiEnabled(true);
				isWifiActivatedByApplication=true;
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			isWifiStateOk = true;

		} else {
			if (wifiManager.isWifiEnabled()) {
				wifiManager.setWifiEnabled(false);
				isWifiActivatedByApplication=false;
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				isWifiActivatedByApplication=false;
				isWifiStateOk=false;
			}
		}
	}
}
